
package com.nmgydy.util;

import java.io.UnsupportedEncodingException;

public class CRC16 {

	private static short[] crcTable = new short[256];
	private static int gPloy = 0x1021; // 生成多项式

	static{
		computeCrcTable();
	}

	private static short getCrcOfByte(int aByte) {
		int value = aByte << 8;
		for (int count = 7; count >= 0; count--) {
			if ((value & 0x8000) != 0) { // 高第16位为1，可以按位异或
				value = (value << 1) ^ gPloy;
			} else {
				value = value << 1; // 首位为0，左移
			}
		}
		value = value & 0xFFFF; // 取低16位的值
		return (short)value;
	}

	/*
	 * 生成0 - 255对应的CRC16校验码
	 */
	private static void computeCrcTable() {
		for (int i = 0; i < 256; i++) {
			crcTable[i] = getCrcOfByte(i);
		}
	}

	public static short getCrc(byte[] by) {
		int crc = 0;
		int length = by.length;
		for (int i = 0; i < length; i++) {
			crc = ((crc & 0xFF) << 8) ^ crcTable[(((crc & 0xFF00) >> 8) ^ by[i]) & 0xFF];
		}
		crc = crc & 0xFFFF;
		return (short)crc;
	}
	
	public static short getCrcJinCai(String s) {
		byte[] by = null;
		
		try {
			by = s.getBytes("GBK");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return -1;
		}
		
		int shift = 0xFFFF;
		int data = 0x0000,val;

		int j=0;
		for(int i=0;i<by.length;i++) {
			if((i % 8) == 0)
				data = (by[j++])<<8;
			val = shift^data;
			shift = shift<<1;
			data = data<<1;
			if((val&0x8000) == 0)
				shift = shift ^ 0x1021;
		}
		
		return (short)shift;
	}

	public static void main(String[] args) throws UnsupportedEncodingException {
		String a = "1500420151208092723000310747100620151208092723P0919108220002420144824014陈东2400.00A6008739000|2400.002015-12-0801";
		//	String a = "1500120151102162506000966247501520151102162506P483510048140001201220907002胡德金5000.00A123456|5000.002015-11-0201";
		byte[] b = a.getBytes();
		System.out.println(b[0]);
		for(int i=0;i<b.length;i++) {
			System.out.print(b[i]);
		}
		System.out.println();
		System.out.println(getCrcJinCai(a));
	}
}